<?php 
	ignore_user_abort(TRUE);
	header("Connection: close\r\n");
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
	<?php require('scripts/header.php'); ?>
</head>

<body>

	<?php require('scripts/body_top.php'); ?>
	
	<div class="content">

<?php

	//Start tracking execution time
	$mtime = microtime(); 
   	$mtime = explode(' ',$mtime); 
   	$mtime = $mtime[1] + $mtime[0]; 
   	$starttime = $mtime;

	// update database with tags.
	
	$exts = array( 'jpg', 'JPG', 'JPEG', 'jpeg', 'PNG', 'png' );
	
	$ss = '/societies/cshotel/snapstitcher';
	
	$path_stitcher = $ss.'/stitcher';
	$path_deepzoomconv = $ss.'/DeepZoomConverter.jar';
	$dir_stitched = $ss.'/stitched/';
	$dir_frames = $ss.'/uploaded/';
	$dir_tmp = $ss.'/tmp/';
	
	// check user
	$stitchid = $_POST['stitchid'];
	$tags = explode(';', stripslashes($_POST['tags']));
	
	$dir_stitched.=$stitchid;
	$dir_tmp.=$stitchid;
	$web_stitched = '/societies/cshotel/public_html/stitched/'.$stitchid;
	
	require 'scripts/db_init.php';
	
	foreach ($tags as $tag){
		if($tag=='') continue;
		$query = "INSERT INTO tags VALUES ('$stitchid','".addslashes($tag)."')";
		mysql_query($query);
	}
	$query="SELECT title, creation FROM image WHERE stitchid=$stitchid";
	$result=mysql_query($query);
	$row = mysql_fetch_array($result);

	$title=$row['title'];
	$creation=$row['creation'];
	echo '<p>Congratulations, you have successfully submitted your images for stitching.</p>';
	echo '<p>You will receive an email when your panorama <i>'.htmlentities($title).'</i> is ready.</p>'; 
	
	// CALL THE STITCHER. RETURN STITCHED IMAGE.

	
	$args = ' --output-name="'.$dir_stitched.'/" --output-format=seadragon --working-directory="' . $dir_tmp.'" --create-thumbnail --thumbnail-suffix="thumb"';
	$args.= ' --deepzoom-converter-jar="'.$path_deepzoomconv.'" ';
	
	$query="SELECT imageid FROM uploads WHERE stitchid=$stitchid";
	$result=mysql_query($query);
	
	$uploaded_imgs = array();
	
	while( $row = mysql_fetch_array($result) ){
		$imgid = $row['imageid'];
		$pth = $dir_frames . $imgid;
		foreach($exts as $ext) {
			if(file_exists($pth.'.'.$ext)){
				$uploaded_imgs[] = $pth . '.' . $ext;
				$uploaded_imgs[] = $pth . '_thumb.jpg';
				$args = $args . '"' . $pth . '.' . $ext . '" ';
				break;
			}
		}
	}
	
	mysql_close();
	
?>
		
	</div>
	
	<?php require('scripts/body_foot.php'); ?>
	
</body>

</html>

<?php
	/*
	function shutdown(){
		mail('cshotel-webmaster@srcf.ucam.org', 'Debugging ' . connection_status(), print_r(error_get_last(), true));
	}
	
	register_shutdown_function('shutdown');
	*/
	
	// allow php script to flush
	//apache_setenv('no-gzip', 1);
	@ini_set('memory_limit', -1);
	@ini_set('output_buffering', 0);
	@ini_set('zlib.output_compression', 0);
	@ini_set('implicit_flush', 1);
	
	// Output PHP file
	flush();
	
	putenv('GSL_DIR=/home/ls475/group_project/gsl/gsl-1.13');
	
	$path_save = getenv('PATH');
	$ld_save = getenv('LD_LIBRARY_PATH');
	
	putenv('PATH=/home/ls475/group_project/enblend/enblend-enfuse-3.2/usr/bin:/home/ls475/group_project/cmake/bin:'.$path_save);
	putenv('LD_LIBRARY_PATH=/home/ls475/group_project/enblend/libplot2c2/usr/lib:/home/ls475/group_project/enblend/libglew1.5/usr/lib:/home/ls475/group_project/openexr/ilmbase-1.0.1/lib:/home/ls475/group_project/openexr/openexr-1.6.1/lib:'.getenv('GSL_DIR').'/lib:'.$ld_save);
	
	// Then execute the stitcher!
	is_dir($dir_stitched) || mkdir( $dir_stitched );
	is_dir($dir_tmp) || mkdir( $dir_tmp );
	
	$output = array('');$return = 0;
	
	//echo '<p>Executing: '. $path_stitcher . $args . ' 2&gt;&amp;1</p>';
	
	//Unlimited execution time
	set_time_limit(0);
	
	$commandline = $path_stitcher . $args . ' 2>&1';
	
	//system($commandline, $return );
	exec($commandline, $output, $return );
	
	$output = implode("\n", $output );
	
	putenv('LD_LIBRARY_PATH='.$ld_save);
	putenv('PATH='.$path_save);
	
	// clean-up files
	deleteDir($dir_tmp);
	
	require 'scripts/db_init.php';
	// delete the uploaded images
	$query="DELETE FROM uploads WHERE stitchid='$stitchid'";
	$result=mysql_query($query) or die(mysql_error());
	
	foreach($uploaded_imgs as $img_file)
		is_file($img_file) && unlink($img_file);
	
	// now lookup details in database, and send the user an e-mail to their panorama
	
	
	$query="SELECT author, title FROM image WHERE stitchid='$stitchid'";
	$result=mysql_query($query) or die(mysql_error());
	$row=mysql_fetch_array($result);
	
	$user=$row['author'];
	$title=$row['title'];
	
	$query="SELECT email FROM user WHERE id='$user'";
	$result=mysql_query($query) or die(mysql_error());
	$row=mysql_fetch_array($result);
	
	$to = $row['email'];
	
	if($return == 0){ // if returnvalue was '0' i.e. success

        // set stitched flag
		$query = "UPDATE image SET stitched=1 WHERE stitchid='$stitchid'";
		$result=mysql_query($query) or die(mysql_error());
		
		// Link to the panorama from public_html
		is_file($web_stitched.'_files') || is_link($web_stitched.'_files') || symlink($dir_stitched.'/panorama', $web_stitched.'_files');
		is_file($web_stitched.'.xml') || is_link($web_stitched.'.xml') || symlink($dir_stitched.'/panorama.xml', $web_stitched.'.xml');
		is_file($web_stitched.'_thumb.jpg') || is_link($web_stitched.'_thumb.jpg') || symlink($dir_stitched.'/thumb.jpg', $web_stitched.'_thumb.jpg');
		
		// And write a nice e-mail
		$subject = "\"{$title}\" has been stitched.";
		$body = "Your panorama can be viewed here:\n\nhttp://www.srcf.ucam.org/cshotel/current/site/gallery.php?stitchid=$stitchid"; 
		
	} else {
	
		// remove image entry from db
		$query = "DELETE FROM image WHERE stitchid='$stitchid'";
		$result=mysql_query($query) or die(mysql_error());
		
		deleteDir($dir_stitched);
		
		$subject = "\"{$title}\" failed to stitch.";
		
		$mtime = microtime(); 
		$mtime = explode(" ",$mtime); 
		$mtime = $mtime[1] + $mtime[0]; 
		$endtime = $mtime; 
		$totaltime = ($endtime - $starttime); 
		
		$body = "Try resubmitting your panorama.\n\n{$commandline}The output of the stitching process was:\n\n{$output}";
		$body.= "\n\nExecution lasted {$totaltime}s.";
	}
	
	mail($to, $subject, $body);
	
	mysql_close(); 

	function deleteDir($dir) {
	   $iterator = new RecursiveDirectoryIterator($dir);
	   foreach (new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file) 
	   {
		  if ($file->isDir())
			 rmdir($file->getPathname());
		  else
			 unlink($file->getPathname());
	   }
	   rmdir($dir);
	}
	
?>